package com.member.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.member.dao.MemberDao;
import com.member.domain.MemberCommand;
import com.member.validator.DeleteValidator;

@Controller
public class PwConfirmController {
	
	@Autowired
	private MemberDao memberDao;
	
	@RequestMapping(value="/member/PwConfirm.do",method=RequestMethod.GET)
	public ModelAndView form(@RequestParam("id")String id){
		MemberCommand memberCommand = memberDao.getMember(id);
		return new ModelAndView("pwConfirm","memberCommand",memberCommand);
	}
	
	@RequestMapping(value="/member/PwConfirm.do",method=RequestMethod.POST)
	public String submit(MemberCommand memberCommand, BindingResult result, HttpSession session){
		
		new DeleteValidator().validate(memberCommand, result);
		if(result.hasErrors()){
			return "pwConfirm";
		}
		
		String pwd = memberDao.userCheck(memberCommand.getId());
		if(!memberCommand.getPassword().equals(pwd)){
			result.rejectValue("password", "invalidPassword");
			return "pwConfirm";
		}

		memberDao.deleteMember(memberCommand);
		session.invalidate();
		return "redirect:/main/index.do";
	}
}
